package com.ocom.payconfig.controller;


import com.ocom.common.constant.PayConfigUrl;
import com.ocom.common.entity.card.EntityXfAccountInfo;
import com.ocom.common.entity.payconfig.EntityXfSignOrder;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.simple.SmsRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.utils.ResultUtil;
import com.ocom.payconfig.client.MqSimpleFeign;
import com.ocom.payconfig.service.*;
import com.ocom.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class AccountController {


    @Autowired
    private XfAccountInfoService xfAccountInfoService;

    @Autowired
    private XfWhiteInfoService xfWhiteInfoService;

    @Autowired
    private XfDeviceInfoService xfDeviceInfoService;

    @Autowired
    private XfSignOrderService xfSignOrderService;

    @Autowired
    private CompanyConfigService companyConfigService;

    @Autowired
    private MqSimpleFeign mqSimpleFeign;

    @Resource
    RedisUtil redisUtil;

    //获取账号信息(getXFAccount)
    @GetMapping(PayConfigUrl.Url_GetXFAccount)
    public Result GetXFAccount(Long comId, Integer pId, @RequestParam(defaultValue = "0",required = false) Integer  accountState){
        if (comId == null){
            log.info("获取账号信息comId为空");
            return ResultUtil.error(ResultEnum.Err_203,"获取账号信息comId为空");
        }
        if (pId == null){
            log.info("获取账号信息pId为空");
            return ResultUtil.error(ResultEnum.Err_203,"获取账号信息pId为空");
        }
    
        return ResultUtil.success(xfAccountInfoService.GetXFAccount(comId,pId,accountState));
    }


    //获取账号信息(getXFAccountByStatus)
    @GetMapping(PayConfigUrl.Url_GetXFAccountByStatus)
    public Result GetXFAccountByStatus(Long comId,Integer pId, Integer accountState){
        if (comId == null){
            log.info("获取账号信息comId为空");
            return ResultUtil.error(ResultEnum.Err_203,"获取账号信息comId为空");
        }
        if (pId == null){
            log.info("获取账号信息pId为空");
            return ResultUtil.error(ResultEnum.Err_203,"获取账号信息pId为空");
        }

        return ResultUtil.success(xfAccountInfoService.GetXFAccount(comId,pId,accountState));

    }

    //初始化账号(addXFAccount)
    @PostMapping(PayConfigUrl.Url_AddXFAccount)
    public Result AddXFAccount(@Validated @RequestBody EntityXfAccountInfo entityXfAccountInfo){
        log.info("添加消费账户 ，【{}】" , entityXfAccountInfo);

        if (entityXfAccountInfo.getComId() == null){
            log.info("初始化账号comId为空");
            return ResultUtil.error(ResultEnum.Err_203,"初始化账号comId为空");
        }
        if (entityXfAccountInfo.getPId() == null){
            log.info("初始化账号pId为空");
            return ResultUtil.error(ResultEnum.Err_203,"初始化账号pId为空");
        }

        if (entityXfAccountInfo.getAccountNo() == null || entityXfAccountInfo.getAccountNo().isEmpty()){
            log.info("初始化账号accountNo为空");
            entityXfAccountInfo.setAccountNo(entityXfAccountInfo.getComId()+"P"+entityXfAccountInfo.getPId());
        }
        if (entityXfAccountInfo.getAccountName() == null || entityXfAccountInfo.getAccountName().isEmpty()){
            log.info("初始化账号accountName为空");
            entityXfAccountInfo.setAccountName(entityXfAccountInfo.getComId()+"P"+entityXfAccountInfo.getPId());
        }
        if (entityXfAccountInfo.getAccountState() == null){
            log.info("初始化账号accountState为空");
            return ResultUtil.error(ResultEnum.Err_203,"初始化账号accountState为空");
        }
        EntityXfAccountInfo entityXfAccountInfo1 = null;
        try {
            //判断账户号唯一
            entityXfAccountInfo1 = xfAccountInfoService.selectAccountNo(entityXfAccountInfo.getComId(), entityXfAccountInfo.getAccountNo());
            if (entityXfAccountInfo1!=null ){
                if(!entityXfAccountInfo1.getPId().equals(entityXfAccountInfo.getPId())){
                    log.info("账号重复{{}}", entityXfAccountInfo1);
                    return ResultUtil.error(ResultEnum.Err_810);
                }
            }
        }catch (Exception exception){

        }

        //判断是否修改
        boolean chageFlag = false ;

        try {
            if (entityXfAccountInfo1 != null){
                //更新；
                if (entityXfAccountInfo.getEndDate() != null || entityXfAccountInfo.getAccTypeId()!=null){
                    if(entityXfAccountInfo.getAccTypeId()!=null && !entityXfAccountInfo.getAccTypeId().equals(entityXfAccountInfo1.getAccTypeId())){
                        entityXfAccountInfo1.setAccTypeId(entityXfAccountInfo.getAccTypeId());
                        chageFlag = true ;
                    }
                    Date bef = entityXfAccountInfo1.getEndDate();
                    if (entityXfAccountInfo.getEndDate() != null){
                        //账户有效期不为空，要更新账户表；
                        entityXfAccountInfo1.setEndDate(entityXfAccountInfo.getEndDate());
                        Integer stateBe = entityXfAccountInfo1.getAccountState();
                        if(entityXfAccountInfo.getEndDate().compareTo(new Date())<0){
                            entityXfAccountInfo1.setAccountState(1);
                        }else{
                            entityXfAccountInfo1.setAccountState(0);
                        }
                        if(!stateBe.equals(entityXfAccountInfo1.getAccountState())){
                            chageFlag = true ;
                        }
                        if(bef == null || !entityXfAccountInfo.getEndDate().equals(bef)){
                            chageFlag = true ;
                        }
                    }
                    if(!chageFlag){
                        return ResultUtil.success();
                    }else{
                        xfAccountInfoService.UpdateXFAccount(entityXfAccountInfo.getComId(),entityXfAccountInfo1);
                    }
                }else{
                    return ResultUtil.success();
                }
            }else {
                // 1. 根据传来的参数新增入库
                xfAccountInfoService.AddXFAccount(entityXfAccountInfo.getComId(), entityXfAccountInfo);
            }
        }catch (Exception exception){
            log.info("初始化账号失败 exception{{}} ",exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_806);
        }
        try {
            Long state = 0L;
            if (entityXfAccountInfo1 != null && entityXfAccountInfo1.getAccountState() ==1){
                state = 1L ;
            }
            //新增白名单：用comId和pId去查询白名单表xf_white_info是否为空
            //a：不为空，删除消费白名单表xf_white_info所有com_id、p_id匹配的记录。
            //b：为空执行下一步
            //   用com_id=@comId，p_id=@pId，state=0，create_time=系统当前时间，新增入库
            xfWhiteInfoService.insertWhiteInfo(entityXfAccountInfo.getComId(),entityXfAccountInfo.getPId(),state);
        }catch (Exception exception){
            log.info("新增消费白名单失败 exception{{}} ",exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_807);
        }

        try {
            //将单位下的所有机器的白名单状态更新为1，
            // Update xf_device_info set list_state=1 where com_id=@comId
            xfDeviceInfoService.updateListState(entityXfAccountInfo.getComId());
        }catch (Exception exception){
            log.info("消费设备白名单更新失败 exception{{}} ",exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_808);
        }
        return ResultUtil.success();
    }

    // 修改账号信息(updateXFAccount)
    @PostMapping(PayConfigUrl.Url_UpdateXFAccount)
    public Result UpdateXFAccount(@Validated @RequestBody EntityXfAccountInfo entityXfAccountInfo){
        if (entityXfAccountInfo.getId() == null){
            log.info("修改账号Id为空");
            return ResultUtil.error(ResultEnum.Err_203,"修改账号Id为空");
        }
        try {
            xfAccountInfoService.UpdateXFAccount(entityXfAccountInfo.getComId(),entityXfAccountInfo);
        }catch (Exception exception){
            log.info("修改账号信息失败 exception{{}} ",exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_809);
        }
        if(entityXfAccountInfo.getAccountState()!=null){
            if (entityXfAccountInfo.getAccountState().equals(1)){
                try {
                    //2.新增白名单：用comId和pId去查询白名单表xf_white_info是否为空
                    //a：不为空，删除消费白名单表xf_white_info所有com_id、p_id匹配的记录。
                    //b：为空执行下一步
                    //   用com_id=@comId，p_id=@pId，state=1，create_time=系统当前时间，新增入库
                    xfWhiteInfoService.insertWhiteInfo(entityXfAccountInfo.getComId(),entityXfAccountInfo.getPId(),1L);
                }catch (Exception exception){
                    log.info("新增消费白名单失败 exception{{}} ",exception.getMessage());
                    return ResultUtil.error(ResultEnum.Err_807);
                }

            }else {
                try {
                    //2.新增白名单：用comId和pId去查询白名单表xf_white_info是否为空
                    //a：不为空，删除消费白名单表xf_white_info所有com_id、p_id匹配的记录。
                    //b：为空执行下一步
                    //   用com_id=@comId，p_id=@pId，state=0，create_time=系统当前时间，新增入库
                    xfWhiteInfoService.insertWhiteInfo(entityXfAccountInfo.getComId(),entityXfAccountInfo.getPId(),0L);
                }catch (Exception exception){
                    log.info("新增消费白名单失败 exception{{}} ",exception.getMessage());
                    return ResultUtil.error(ResultEnum.Err_807);
                }
            }
        }


        //3.将单位下的所有机器的白名单状态更新为1，Update xf_device_info set list_state=1 where com_id=@comId
        try {
            //将单位下的所有机器的白名单状态更新为1，
            // Update xf_device_info set list_state=1 where com_id=@comId
            xfDeviceInfoService.updateListState(entityXfAccountInfo.getComId());
        }catch (Exception exception){
            log.info("消费设备白名单更新失败 exception{{}} ",exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_808);
        }
        return ResultUtil.success();
    }

    @PostMapping(PayConfigUrl.Url_SetXFWhiteInfo)
    public Result setXFWhiteInfo(Long comId,Long pId,Long state){

        try {
            //2.新增白名单：用comId和pId去查询白名单表xf_white_info是否为空
            //a：不为空，删除消费白名单表xf_white_info所有com_id、p_id匹配的记录。
            //b：为空执行下一步
            //   用com_id=@comId，p_id=@pId，state=0，create_time=系统当前时间，新增入库
            xfWhiteInfoService.insertWhiteInfo(comId,pId,state);
        }catch (Exception exception){
            log.info("新增消费白名单失败 exception{{}} ",exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_807);
        }
        //3.将单位下的所有机器的白名单状态更新为1，Update xf_device_info set list_state=1 where com_id=@comId
        try {
            //将单位下的所有机器的白名单状态更新为1，
            // Update xf_device_info set list_state=1 where com_id=@comId
            xfDeviceInfoService.updateListState(comId);
        }catch (Exception exception){
            log.info("消费设备白名单更新失败 exception{{}} ",exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_808);
        }
        return ResultUtil.success();
    }

    //定时任务更新过期账户为禁用（/accountDisabled）
    @PostMapping(PayConfigUrl.URL_accountDisabled)
    public Result accountDisabled() {
        accountDisabledTimerHandle(100L);
        accountDisabledTimerHandle(600L);
        return ResultUtil.success();
    }

    private void accountDisabledTimerHandle(Long companyId) {
        ArrayList<Long> comIds = new ArrayList<>();

        List<EntityXfAccountInfo> list = xfAccountInfoService.selectAccountInfos(companyId, null);
        if (list == null || list.size() == 0) {
            return;
        }
        for (EntityXfAccountInfo entityXfAccountInfo : list) {
            if (entityXfAccountInfo.getId() == null) {
                log.info("修改账号Id为空");
                continue;
            }
            try {
                entityXfAccountInfo.setAccountState(1);
                xfAccountInfoService.UpdateXFAccount(entityXfAccountInfo.getComId(), entityXfAccountInfo);
                if (!comIds.contains(entityXfAccountInfo.getComId())) {
                    comIds.add(entityXfAccountInfo.getComId());
                }
            } catch (Exception exception) {
                log.info("修改账号信息失败 exception{{}} ", exception.getMessage());
                continue;
            }
            if (entityXfAccountInfo.getAccountState() != null) {
                if (entityXfAccountInfo.getAccountState().equals(1)) {
                    try {
                        //2.新增白名单：用comId和pId去查询白名单表xf_white_info是否为空
                        //a：不为空，删除消费白名单表xf_white_info所有com_id、p_id匹配的记录。
                        //b：为空执行下一步
                        //   用com_id=@comId，p_id=@pId，state=1，create_time=系统当前时间，新增入库
                        xfWhiteInfoService.insertWhiteInfo(entityXfAccountInfo.getComId(), entityXfAccountInfo.getPId(), 1L);
                    } catch (Exception exception) {
                        log.info("新增消费白名单失败 exception{{}} ", exception.getMessage());
                    }

                }
            }

        }

        try {
            //将单位下的所有机器的白名单状态更新为1，
            // Update xf_device_info set list_state=1 where com_id=@comId
            xfDeviceInfoService.updateListState(companyId, comIds);
        } catch (Exception exception) {
            log.info("消费设备白名单更新失败 exception{{}} ", exception.getMessage());
        }
    }


    //定时任务账号到期提前三天发送短信(/accountExpiration)
    @GetMapping(PayConfigUrl.URL_accountExpiration)
    public Result accountExpiration() {
        accountExpirationHandle(100L);
        accountExpirationHandle(600L);
        return ResultUtil.success();
    }


    private void accountExpirationHandle(Long companyId) {

        List<Long> comIds = companyConfigService.getComIdsByKey(companyId, "accountExpiration", "true");

        if (comIds == null) {
            return;
        }
        Date now1 = null;
        try {
            now1 = DateUtils.getDate(DateUtils.getDate(), "yyyy-MM-dd");
        } catch (ParseException e) {
            return;
        }
        Date after3Day = DateUtils.addDays(now1, 3);

        List<EntityXfAccountInfo> list = xfAccountInfoService.selectAccountInfosNotice(companyId, comIds, after3Day);
        if (list == null || list.size() == 0) {
            return;
        }

        List<Long> pIds = list.stream().map(EntityXfAccountInfo::getPId).collect(Collectors.toList());

        List<EntityXfSignOrder> xfSignOrderList = xfSignOrderService.getUserSignPhones(companyId, pIds);

        if (xfSignOrderList == null || xfSignOrderList.size() == 0) {
            return;
        }

        for (EntityXfSignOrder entityXfSignOrder : xfSignOrderList) {
            String phone = entityXfSignOrder.getBank();
            if (!CommonUtil.isNull(phone) && phone.length() == 11) {
                String insufficientBalanceMsg = "accountExpiration:" + entityXfSignOrder.getComId() + ":" + phone;
                if (redisUtil.lock(insufficientBalanceMsg, 60 * 60)) {
                    SmsRequest smsRequest = new SmsRequest();
                    smsRequest.setSecretId("AKIDcLzhN0a8e8eChEnaQG8zpifcabfnu5JX");
                    smsRequest.setSecretKey("Kh6VozznPn13ECwSlphN9jCVaRLTPIPa");
                    smsRequest.setSignName("鑫澳康科技");
                    smsRequest.setSdkAppId("1400314290");
                    smsRequest.setTemplateId("2180762");
                    smsRequest.setPhone(phone);
                    mqSimpleFeign.FySms(smsRequest);
                }
            }
        }
    }
}
